package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.ScrollResult;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

@Service
public class BlogServiceImpl extends
        ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService iFollowService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog->{
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //通过id查询blog
        Blog blog = getById(id);
        if(blog==null) {
            return Result.fail("博客不存在!!!");
        }
        queryBlogUser(blog);
        //是否被点赞过
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    //判断用户是否已经点过赞了
    private void isBlogLiked(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，无需查询是否点赞
            return;
        }
        Long userId = user.getId();
        // 2.判断当前登录用户是否已经点赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);
    }

    /**
     * 用户是否点赞
     */
    @Override
    public Result likeBlog(Long id) {
        //得到登陆用户id
        Long userId = UserHolder.getUser().getId();
        String key = BLOG_LIKED_KEY + id;
        //判断该用户有没有点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //用户是否点赞
        if(score==null) {
            //用户没有点赞
            //更新数据库->点赞数+1
            boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            //数据库更新成功,同时更新Redis,把该用户加入到set集合中代表已经点过赞了
            if(isSuccess) {
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else {
            //用户已经点过赞了
            //更新数据库->点赞数-1
            boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
            //数据库更新成功,更新Redis,将该用户从set集合中移除->取消点赞
            if(isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    //查询点赞列表
    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        //查询出前top5的用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        //转换为long存放到集合中
        if(top5==null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",",ids);
        //查询出对应的用户返回
        List<UserDTO> userDTOs = userService.query().in("id", ids).last("ORDER BY FIELD(id,+" + join + ")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOs);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        save(blog);
        /**
         * 新增功能 : 把这个博文推送给它的所有粉丝
         */
        Long userId = user.getId();
        //查询当前用户的所有粉丝
        List<Follow> followList = iFollowService.query()
                .eq("follow_user_id", userId).list();
        //给所有粉丝推送博文
        for (Follow follow : followList) {
            //得到粉丝的id
            Long followId = follow.getId();
            //每一个粉丝都会有自己的收件箱
            String key = FEED_KEY + followId;
            //推送到粉丝的收件箱
            stringRedisTemplate.opsForZSet().
                    add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 分页查询当前用户关注的人的博文笔记
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Integer max, Integer offset) {
        //1.查询当前用户
        Long userId = UserHolder.getUser().getId();
        //2.找出当前用户的收件箱
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //3.解析出收件箱的信息(blogId,minTime,offset)
        ArrayList<Long> listIds = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //得到博客id
            Long id = Long.valueOf(tuple.getValue());
            listIds.add(id);
            //得到博客的时间戳
            long time = tuple.getScore().longValue();
            if(minTime == time) {
                os++;
            }else {
                minTime  = time;
                os  = 1;
            }
        }
        long x = 10l;
        int y =(int)x;
        String joinStr = StrUtil.join(",", listIds);
        //4.根据blogId查询出关注的人的所有博文
        List<Blog> blogs = query().in("id", listIds).
                last("ORDER BY FIELDS(id," + joinStr + ")").list();
        for (Blog blog : blogs) {
            //查询博客用户
            queryBlogUser(blog);
            //是否被点赞过
            isBlogLiked(blog);
        }
        //5.将所有博文进行封装ScrollResult
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setOffset(os);
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }

    private Result getResult(Integer max, Integer offset) {
        //1.查询出当前用户
        Long userId = UserHolder.getUser().getId();
        //2.找到用户对应的收件箱-->注意是实现分页查询
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //3.解析出收件箱内容(blog_id,minTime,offset)
        long minTime = 0;
        int os = 1;//偏移量->与最小时间戳相同的个数
        ArrayList<Long> blogIds = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //value : 博客id
            String idStr = tuple.getValue();
            blogIds.add(Long.valueOf(idStr));
            //时间戳
            long time = tuple.getScore().longValue();
            if(minTime == time) {
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        String joinStr = StrUtil.join(",", blogIds);
        //4.根据收件箱内容查询出博文信息
        //根据blogIds的博文id查询出博文
        List<Blog> blogs =
                query().in("id", blogIds).
                        last("ORDER BY FIELDS(id," + joinStr + ")").list();
        for (Blog blog : blogs) {
            //查询博客用户
            queryBlogUser(blog);
            //是否被点赞过
            isBlogLiked(blog);
        }
        //5.封装分页结果
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(os);
        return Result.ok(scrollResult);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}